package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.cache.service.IUserInfoCacheService;
import cn.wolfcode.luowowo.cache.service.IVerifyCodeCacheService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.common.util.Consts;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import com.alibaba.fastjson.JSON;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

@Controller
public class LoginController {

    @Reference
    private IUserInfoService userInfoService;


    @RequestMapping("/checkPhone")
    @ResponseBody
    public Object checkPhone(String phone){

        return userInfoService.checkPhone(phone);
    }


    @Reference
    private IVerifyCodeCacheService verifyCodeCacheService;
    @RequestMapping("/sendVerifyCode")
    @ResponseBody
    public Object sendVerifyCode(String phone){
        AjaxResult result = new AjaxResult();
        //检查改手机号的验证码是否已经发送
        String verifyCode = verifyCodeCacheService.getVerifyCode(phone);
        //如果已经发送,发送错误信息
        if (verifyCode != null){
            result.mark("验证码已发送,请勿重复操作");
            return result;
        }
        //,如果没有发送,产生验证码
        verifyCode = UUID.randomUUID().toString().substring(0, 4);
        System.err.println("亲,您的验证码是"+ verifyCode + "请在60s内使用");
        //缓存验证码
        verifyCodeCacheService.setVerifyCode(phone,verifyCode);
        return result;
    }

    @RequestMapping("/userRegist")
    @ResponseBody
    public Object userRegist(String phone,String nickname,String password,String rpassword,String verifyCode){
        AjaxResult result = userInfoService.userRegist(phone, nickname, password, rpassword, verifyCode);
        return result;
    }


    @Reference
    private IUserInfoCacheService userInfoCacheService;

    @RequestMapping("/userLogin")
    @ResponseBody
    public Object userLogin(String phone, String password, HttpServletResponse response, HttpSession session){
        AjaxResult result = userInfoService.userLogin(phone, password);
        //登录成功,返回token给用户
        if (result.isSuccess()){
            //通过cookie返回去
             String token = (String) result.getData();
            Cookie cookie = new Cookie(Consts.USER_INFO_TOKEN,token);
            response.addCookie(cookie);
            //将用户信息存入session中
            String userInfo = userInfoCacheService.getUserInfo(token);
            session.setAttribute(Consts.USER_INFO,JSON.parseObject(userInfo, UserInfo.class));//将json解析成java对象
        }
        return result;
    }
}
